package com.haima.sage.bigdata.api.frame.datatype.impl;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.haima.sage.bigdata.api.common.Constants;
import com.haima.sage.bigdata.api.frame.datatype.DataTypeService;

public class DateStringDataTypeService extends DataTypeService<String> {
    private static final Logger LOG = LogManager.getLogger(DateStringDataTypeService.class);
    private String pattern;
    private SimpleDateFormat sdf1;
    private SimpleDateFormat sdf2;
    private Pattern regex = Pattern.compile("\\d+");
    private SimpleDateFormat dst;

    public DateStringDataTypeService(String fromPattern, String distPattern) {
        this.pattern = fromPattern;

        try {
            if (null == pattern) {
                pattern = "yyyy-MM-dd HH:mm:ss";
            }
            sdf1 = new SimpleDateFormat(pattern, Locale.ENGLISH);
            sdf2 = new SimpleDateFormat(pattern, Locale.CHINESE);
        } catch (Exception e) {
            LOG.error("not support date pattern:{}", pattern, e);
        }
        String format = distPattern;
        if (format == null || pattern.length() == 0) {
            format = Constants.DATE_PATTERN;
        }
        this.dst = new SimpleDateFormat(format);
    }

    @Override
    public String trans(Object value) throws Exception {
        if (null == value) {
            return null;
        }
        if (value instanceof Timestamp) {
            return dst.format(new Date(((Timestamp) value).getTime()));
        } else if (value instanceof Date) {
            return dst.format((Date) value);
        } else if (value instanceof Double) { // json 反序列化后
            return dst.format(new Date(((Double) value).longValue()));
        } else if (value instanceof Long) { // Java最常用的时间标签
            return dst.format(new Date((Long) value));
        } else if (value instanceof Integer) { // UNIX最常用的时间标签
            return dst.format(new Date(((Integer) value) * 1000));
        } // 格式 解析
        String tmp = value.toString().trim();
        if (regex.matcher(tmp).matches()) {
            if (tmp.length() == 13) {
                long time = Long.parseLong(tmp);
                return dst.format(new Date(time));
            } else if (tmp.length() == 10) {
                long time = Long.parseLong(tmp);
                return dst.format(new Date(time * 1000));
            }
        }
        try {
            return dst.format(sdf1.parse(tmp));
        } catch (ParseException e) {
            return dst.format(sdf2.parse(tmp));
        }
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}
